package com.dy.yunying.biz.controller.manage;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dy.yunying.api.dto.ChannelManageDto;
import com.dy.yunying.api.entity.ChannelManageDO;
import com.dy.yunying.api.req.ChannelManageReq;
import com.dy.yunying.api.vo.ChannelManageVo;
import com.dy.yunying.biz.config.YunYingProperties;
import com.dy.yunying.biz.dao.manage.ext.ChannelManageDOMapperExt;
import com.dy.yunying.biz.service.manage.ChannelManageService;
import com.dy.yunying.biz.utils.StringUtil;
import com.pig4cloud.pig.common.core.util.CommonUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Slf4j
@RestController
@RequestMapping("/chlmanage")
public class ChannelManageController {

	@Autowired
	private ChannelManageService channelManageService;

	@Autowired
	private ChannelManageDOMapperExt promotionChannelDOMapperExt;

	@Autowired
	private YunYingProperties yunYingProperties;

	/***
	 * 添加主渠道,修改主渠道名称
	 */
	@SysLog("添加主渠道")
	@RequestMapping(value = "/addParent.json")
	public R<Integer> saveParentchl(ChannelManageDto channel) {
		if (StringUtils.isBlank(channel.getChnname())) {
			return R.failed("主渠道名称不能为空");
		}
		if (!Objects.nonNull(channel.getPlatform())) {
			return R.failed("平台类型不能为空");
		}
		if (channel.getChnname().length() > 20) {
			return R.failed("主渠道名称长度不能大于20");
		}
		List<ChannelManageVo> channelManageVo = promotionChannelDOMapperExt.queryParentChlByName(channel);
		if (channelManageVo.size() > 0) {
			return R.failed("主渠道名称数据库已存在");
		}
		R<Integer> result = null;
		channel.setCreator(Long.valueOf(SecurityUtils.getUser().getId()));
		channel.setEditor(Long.valueOf(SecurityUtils.getUser().getId()));
		channel.setPid(0);
		channel.setIsdelete(0);
		channel.setChncode(String.valueOf(System.currentTimeMillis()));
		channel.setUpdatetime(new Date());
		channel.setCreatetime(new Date());
		result = channelManageService.saveParentchl(channel);
		if (Objects.nonNull(result)) {
			channelManageService.savedefaultchl(channel);
		}
		return result;
	}

	/***
	 * 查询主渠道列表·
	 */
	@SysLog("渠道管理")
	@RequestMapping(value = "/getParentChlList")
	public R queryParentchlList(ChannelManageReq req) {
		IPage<ChannelManageVo> data = channelManageService.queryParentchlList(req);
		return R.ok(data, "查询成功");
	}

	/**
	 * 编辑主渠道
	 */
	@SysLog("编辑主渠道")
	@RequestMapping("/editChannel.json")
	public R updateParentchl(ChannelManageDto channel) {
		if (StringUtils.isBlank(channel.getChnname())) {
			return R.failed("主渠道名称不能为空");
		}
		if (channel.getChnname().length() > 20) {
			return R.failed("主渠道名称长度不能大于20");
		}
		List<ChannelManageVo> channelManageVo = promotionChannelDOMapperExt.queryParentChlByName(channel);
		if (channelManageVo.size() > 0) {
			if (channelManageVo.get(0).getId().intValue() != channel.getId()) {
				return R.failed("主渠道名称数据库已存在");
			}
		}
		channel.setUpdatetime(new Date());
		R data = channelManageService.updateParentchl(channel);
		return data;
	}

	/**
	 * 添加子渠道（根据主渠道名称 添加对应子渠道）
	 */
	@SysLog("添加子渠道")
	@RequestMapping(value = "/addChannel")
	public R savechl(ChannelManageDto channel) {
		R result = null;
		if (StringUtils.isBlank(channel.getSonname())) {
			return R.failed("子渠道名称不能为空");
		}
		if (channel.getSonname().length() > 20) {
			return R.failed("子渠道名称长度不能大于20");
		}
		channel.setPid(channel.getSonChannelId());
		channel.setParentCode(channel.getChncode());
		channel.setChnname(channel.getSonname());
		channel.setIsDefault(0);
		result = channelManageService.savechl(channel);
		return result;
	}

	/**
	 * 查询子渠道列表
	 */
	@SysLog("子渠道列表")
	@RequestMapping(value = "/getChlList")
	public R queryChlList(ChannelManageReq req) {
		IPage<ChannelManageVo> data = channelManageService.queryChlList(req);
		return R.ok(data, "查询成功");
	}

	/**
	 * 编辑子渠道列表
	 */
	@SysLog("编辑子渠道")
	@RequestMapping(value = "/editChl.json")
	public R editChlList(ChannelManageDto channel) {
		if (StringUtils.isBlank(channel.getSonname())) {
			return R.failed("子渠道名称不能为空");
		}
		if (channel.getSonname().length() > 20) {
			return R.failed("子渠道名称长度不能大于20");
		}
		R data = channelManageService.updateChl(channel);
		return data;
	}

	/**
	 * 获取cps主渠道
	 */
	@RequestMapping(value = "/cps/getParentChannel")
	public R cpsParentchl() {
		ChannelManageVo channelManageVo = channelManageService.getVOByPK(yunYingProperties.getCpsParentChannelId());
		if (Objects.isNull(channelManageVo)){
			return R.failed("cps主渠道不存在，请先配置");
		}
		return R.ok(channelManageVo);
	}

	/**
	 * 查询cps子渠道列表
	 */
	@SysLog("子渠道列表")
	@RequestMapping(value = "/cps/getChlList")
	public R queryCpsChlList(@RequestBody ChannelManageReq req) {
		IPage<ChannelManageVo> data = channelManageService.queryChlList(req);
		return R.ok(data, "查询成功");
	}

	/**
	 * cps添加子渠道（根据主渠道名称 添加对应子渠道）
	 */
	@SysLog("添加子渠道")
	@RequestMapping(value = "/cps/addChannel")
	@PreAuthorize("@pms.hasPermission('cps_add_channel')")
	public R cpsSavechl(ChannelManageDto channel) {
		if (StringUtils.isBlank(channel.getSonname())) {
			return R.failed("子渠道名称不能为空");
		}
		if (channel.getSonname().length() > 20) {
			return R.failed("子渠道名称长度不能大于20");
		}
		channel.setPid(channel.getSonChannelId());
		channel.setParentCode(channel.getChncode());
		channel.setChnname(channel.getSonname());
		channel.setIsDefault(0);
		return channelManageService.saveCpsChl(channel);
	}

	/**
	 * 编辑子渠道列表
	 */
	@SysLog("编辑子渠道")
	@RequestMapping(value = "/cps/editChannel")
	@PreAuthorize("@pms.hasPermission('cps_edit_channel')")
	public R cpsEditChl(ChannelManageDto channel) {
		if (StringUtils.isBlank(channel.getSonname())) {
			return R.failed("子渠道名称不能为空");
		}
		if (channel.getSonname().length() > 20) {
			return R.failed("子渠道名称长度不能大于20");
		}
		if (Objects.nonNull(channel.getBuckleRate())){
			if (channel.getBuckleRate().compareTo(new BigDecimal("100")) > 0 || channel.getBuckleRate().compareTo(BigDecimal.ZERO) <0){
				return R.failed("扣量比例必须是0~100之间两位小数");
			}
			if (!CommonUtils.isMoney(channel.getBuckleRate().toPlainString(), 2)){
				return R.failed("扣量比例必须是0~100之间的两位小数");
			}
		}
		R data = channelManageService.updateChl(channel);
		return data;
	}

	/**
	 * 删除
	 */
	@SysLog("删除子渠道")
	@RequestMapping(value = "/cps/deleteChannel")
	@PreAuthorize("@pms.hasPermission('cps_delete_channel')")
	public R cpsEditChl(Integer id) {
		try {
			if (id == null){
				return R.failed("子渠道id不能为空");
			}
			channelManageService.removeById(id);
			return R.ok("删除子渠道成功");
		} catch (Exception e) {
			log.error("删除子渠道失败，失败原因：{}",e);
			return R.failed("删除子渠道失败");
		}
	}

	/**
	 * 获取所有cps渠道子渠道列表
	 */
	@RequestMapping(value = "/cps/getAllChlList")
	public R queryAllCpsChlList() {
		List<ChannelManageDO> list = channelManageService.list(Wrappers.<ChannelManageDO>lambdaQuery().eq(ChannelManageDO::getPid, yunYingProperties.getCpsParentChannelId()));
		return R.ok(list, "查询成功");
	}
}
